const _H5_apiDomain = process.env.VUE_APP_H5_apiDomain;

import axios from "axios";
import { Toast } from "vant";

function request(opt) {
  opt = opt || {};
  opt.method = (opt.method || "POST").toUpperCase();
  opt.url = _H5_apiDomain + opt.url.trim() || "";
  opt.data = opt.data || null;
  let isNeedErrorToast = opt.isNeedErrorToast === false ? false : true; // 接口报错时是否不需要错误提示
  var _SourceType = 1; // app-h5
  var _key = "";
  var _signCode = "789649779a49df79sad7fa9sd87";
  var _time = Math.round(new Date().getTime() / 1000).toString();

  var _dataOpts = {
    Header: {
      SourceType: _SourceType,
      userTicket: window.sessionStorage.getItem("cangpei_user_ticket"),
      SignCode: _signCode,
      machineKey: _key,
      timeStamp: _time,
      version: 4.1,
    },
    Body: opt.data,
  };
  opt.data = _dataOpts;

  var isShowLoading = opt.isShowLoading || false;

  if (isShowLoading) {
    Toast.loading({
      message: "加载中...",
      forbidClick: true,
      duration: 10000,
      type: "loading",
    });
  }

  var myPromise = new Promise(function(resolve, reject) {
    axios({
      method: opt.method || "POST",
      url: opt.url,
      headers: {
        "content-type": "application/json",
      },
      data: _dataOpts,
      dataType: opt.dataType || "JSON",
      noShowLoading: opt.noShowLoading,
    })
      .then((res) => {
        if (isShowLoading) {
          setTimeout(() => {
            Toast.clear();
          }, 500);
        }

        if (res.data.Header.ErrorCode != 0) {
          Toast({
            duration: 5000, // 持续展示 toast
            message: res.data.Header.Message,
          });
          return;
        }
        resolve(res.data.Body);
      })
      .catch((err) => {
        if (isShowLoading) {
          setTimeout(() => {
            Toast.clear();
          }, 3000);
        }
        if (err.status) {
          Toast(err.errMsg);
        } else {
          if (isNeedErrorToast) {
            Toast("网络环境不稳定，请稍后再试");
          }
        }
        reject(err);
        return false;
      });
  });

  return myPromise;
}

export default request;
